package me.ratel.demo.eBook.application.impl;

import com.alibaba.fastjson.JSONObject;
import me.ratel.demo.eBook.application.IOrderingService;
import me.ratel.demo.eBook.application.IUserService;
import me.ratel.demo.eBook.domain.model.order.IDGenerator;
import me.ratel.demo.eBook.domain.model.order.IOrderDao;
import me.ratel.demo.eBook.domain.model.order.Order;
import me.ratel.demo.eBook.domain.model.user.User;
import me.ratel.demo.wechat.WeChatService;
import me.ratel.demo.wechat.entities.BrandWCPayRequest;
import me.ratel.demo.wechat.WeChat;
import me.ratel.demo.wechat.WeChatConstants;
import me.ratel.demo.wechat.entities.UnifiedOrderResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Administrator
 * @time 2016/9/17 16:53
 */
@Service
public class OrderingService implements IOrderingService {
    private static final Logger log = LoggerFactory.getLogger(OrderingService.class);

    @Autowired private IUserService userService;

    @Autowired private IOrderDao orderDao;

    private static final String notifyURL = "http://40lsgy1.tunnel.qydev.com/eBook/order/notify";

    // 生成图书订单
    @Transactional
    @Override public BrandWCPayRequest generatePrepayId(Integer userId, Integer bookId, Integer price) {
        User user = userService.get(userId);

        // 生成商户订单
        String orderId = IDGenerator.generateUniqueOrderId();

        // 调用统一下单API
        WeChatService wechatService = WeChat.newWeChat(
                "wx08379b83fa805962",
                "4d0c055d9d7256bc49131bec149acc24",
                "1357882102",
                "3520fc5282a8fd12ee4f4c1cae7d7e1e"
        );
        UnifiedOrderResponse unifiedOrderResponse
                = wechatService.unifiedOrder("深入理解Java虚拟机", new JSONObject(), notifyURL, orderId, user.getOpenId(), "123.12.12.123", price, WeChatConstants.TradeType.JSAPI.getValue());

        orderDao.save(new Order(bookId, userId, price, orderId, unifiedOrderResponse.getPrepayId()));

        // 返回预付单信息
        return wechatService.getBrandWCPayRequest(unifiedOrderResponse.getPrepayId());
    }
}
